#include "mainwindow.h"
#include <QtXmlPatterns/QXmlQuery>

MainWindow::MainWindow(const QString &FileConfig, DbConnection *Connection, QWidget *parent)
    : QMainWindow(parent), m_db(Connection),m_viewer(Connection),m_toolBar(0),
    m_fileConfig(FileConfig)
{
    setWindowTitle(tr("AWSD"));
    connect(&m_viewer,SIGNAL(state_message(QString,int,QColor)),this,SIGNAL(init_message(QString,int,QColor)));
    connect(&m_viewer,SIGNAL(state_message(QString,int)),this->statusBar(),SLOT(showMessage(QString,int)));
    connect(&m_viewer,SIGNAL(toolBarChange(QList<QAction*>)),this,SLOT(setToolBar(QList<QAction*>)));
}

bool MainWindow::initialization()
{
    hide();
    if(!readSettings()) return false;
    if(!m_viewer.initialization()) return false;
    setCentralWidget(&m_viewer);
    DbConnection::QueryResult res = m_db->execute("select =schema=.in_uid()");
    if(res.success())
    {}
    show();
    return true;
}
void MainWindow::closeEvent(QCloseEvent *event)
{
    if(m_viewer.isWasChangedItem())
    {
        QMessageBox box(this);
        box.setText(tr("Изменения будут потеряны. Продолжить?"));
        box.setIcon(QMessageBox::Question);
        box.setWindowTitle(tr("Выход"));
        QAbstractButton* yes=box.addButton(tr("Да"),QMessageBox::NoRole);
        box.addButton(tr("Нет"),QMessageBox::NoRole);
        box.exec();
        if(box.clickedButton()==yes)
            event->accept();
        else
            event->ignore();
    }
}

MainWindow::~MainWindow()
{
    delete m_db;
    saveSettings();
}

bool MainWindow::readSettings()
{
    QFile file(m_fileConfig);
    if(file.open(QIODevice::ReadOnly|QIODevice::Text))
    {
        QRect rect=geometry();
        QTextStream in(&file);
        QString xml, res;
        while(!in.atEnd()) xml.append(in.readLine()+"\n");
        file.close();
        QXmlQuery q;
        q.setFocus(xml);
        q.setQuery("/settings/states/element[@name=\"MainWindow\"]/geometry/left/@value/string()");
        if(q.evaluateTo(&res))
        {
            res=res.replace("\n","");
            rect.setX(res.toInt());
        }
        else
            rect.setX(10);

        q.setQuery("/settings/states/element[@name=\"MainWindow\"]/geometry/top/@value/string()");
        if(q.evaluateTo(&res))
        {
            res=res.replace("\n","");
            rect.setY(res.toInt());
        }
        else
            rect.setY(10);

        q.setQuery("/settings/states/element[@name=\"MainWindow\"]/geometry/height/@value/string()");
        if(q.evaluateTo(&res))
        {
            res=res.replace("\n","");
            rect.setHeight(res.toInt());
        }
        else
            rect.setHeight(200);
        q.setQuery("/settings/states/element[@name=\"MainWindow\"]/geometry/width/@value/string()");
        if(q.evaluateTo(&res))
        {
            res=res.replace("\n","");
            rect.setWidth(res.toInt());
        }
        else
            rect.setWidth(200);
        setGeometry(rect);
        QList <int> splitter_sizes;
        q.setQuery("/settings/states/element[@name=\"Splitter\"]/geometry/left/@value/string()");
        if(q.evaluateTo(&res))
        {
            res=res.replace("\n","");
            splitter_sizes.append(res.toInt());
        }
        q.setQuery("/settings/states/element[@name=\"Splitter\"]/geometry/right/@value/string()");
        if(q.evaluateTo(&res))
        {
            res=res.replace("\n","");
            splitter_sizes.append(res.toInt());
        }
        if(splitter_sizes.count()==2)
            m_viewer.splitter()->setSizes(splitter_sizes);
        else
        {
            splitter_sizes.append(100);
            splitter_sizes.append(100);
            m_viewer.splitter()->setSizes(splitter_sizes);
        }
        q.setQuery("/settings/states/element[@name=\"TreeDoc\"]/commonNumering/@value/string()");
        if(q.evaluateTo(&res))
        {
            res=res.replace("\n","");
            bool commoNumering = (res=="true");
            m_viewer.setCommonNumering(commoNumering);
        }
        q.setQuery("/settings/states/element[@name=\"TreeDoc\"]/historyMaxSize/@value/string()");
        if(q.evaluateTo(&res))
        {
            res=res.replace("\n","");
            int size = res.toInt();
            m_viewer.setHistoryMaxSize(size);
        }
        q.setQuery("/settings/states/element[@name=\"TreeDoc\"]/highlight/@value/string()");
        if(q.evaluateTo(&res))
        {
            res=res.replace("\n","");
            bool on = (res=="true");
            m_viewer.setHighlighterOn(on);
        }
        q.setQuery("/settings/states/element[@name=\"TreeDoc\"]/update_interval/@value/string()");
        if(q.evaluateTo(&res))
        {
            res=res.replace("\n","");
            m_viewer.setRefreshInterval(30);
        }
        else
            m_viewer.setRefreshInterval(30);
    }
    else
    {
        emit init_message(tr("Невозможно прочитать файл конфигурации."),Qt::AlignBottom,Qt::red);
        return false;
    }
    return true;
}

void MainWindow::saveSettings()
{
    QFile file(m_fileConfig);
    if(file.open(QIODevice::ReadOnly|QIODevice::Text))
    {
        QRect rect=geometry();
        QTextStream in(&file);
        QString xml,tmp;
        while(!in.atEnd()) xml.append(in.readLine()+"\n");
        file.close();
        QRegExp rx("<element name=\"MainWindow\">.*</element>");
        rx.setMinimal(true);
        tmp.append(   "<element name=\"MainWindow\">\n");
        tmp.append(   "         <geometry>\n");
        tmp.append(tr("             <left value=\"%1\"/>\n").arg(rect.x()));
        tmp.append(tr("             <top value=\"%1\"/>\n").arg(rect.y()));
        tmp.append(tr("             <height value=\"%1\"/>\n").arg(rect.height()));
        tmp.append(tr("             <width value=\"%1\"/>\n").arg(rect.width()));
        tmp.append(   "         </geometry>\n");
        tmp.append(tr("         <capTitle value=\"%1\"/>\n").arg(windowTitle().replace(QRegExp("\".*\""),"")));
        tmp.append(   "       </element>");
        xml=xml.replace(rx,tmp);
        tmp.clear();
        rx.setPattern("<element name=\"Splitter\">.*</element>");
        tmp.append(   "<element name=\"Splitter\">\n");
        tmp.append(   "         <geometry>\n");
        tmp.append(tr("             <left value=\"%1\"/>\n").arg(m_viewer.splitter()->sizes().at(0)));
        tmp.append(tr("             <right value=\"%1\"/>\n").arg(m_viewer.splitter()->sizes().at(1)));
        tmp.append(   "         </geometry>\n");
        tmp.append(   "       </element>");
        xml=xml.replace(rx,tmp);
        tmp.clear();
        QXmlQuery q;
        q.setFocus(xml);
        q.setQuery("/settings/states/element[@name=\"TreeDoc\"]");
        if(q.evaluateTo(&tmp))
        {
            rx.setPattern("<highlight .*/>");
            tmp=tmp.replace(rx,tr("<highlight value=\"%1\"/>").arg(m_viewer.highlight()?"true":"false"));
        }
        rx.setPattern("<element name=\"TreeDoc\">.*</element>\n");
        xml=xml.replace(rx,tmp);
        if(file.open(QIODevice::WriteOnly|QIODevice::Text))
        {
            QTextStream out(&file);
            out<<xml;
            file.close();
        }
    }
}

void MainWindow::setToolBar(QList<QAction *> actions)
{
   if(m_toolBar!=0)
       removeToolBar(m_toolBar);
   m_toolBar = new QToolBar(tr("Панель инструментов"),this);
   m_toolBar->setMovable(false);
   m_toolBar->addActions(actions);
   /*QAction* help = m_toolBar->addAction(QIcon(":/help"),tr("Справка"));
   connect(help,SIGNAL(triggered()),this,SLOT(showHelp()));*/
   addToolBar(m_toolBar);
}

void MainWindow::showHelp()
{}
